import { Link, useLocalSearchParams, useRouter, type Href } from 'expo-router';
import { useMemo, useState } from 'react';
import {
  KeyboardAvoidingView,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

import { useAuth } from '@/context/auth-context';
import { encodeRedirectParam, normalizeRedirectParam, type RedirectTarget } from '@/utils/redirect';

const palette = {
  background: '#fff3f9',
  card: '#ffffff',
  accent: '#ff8fb1',
  accentDeep: '#ff6a9b',
  textPrimary: '#2f1f2b',
  textMuted: '#6a566a',
  inputBackground: '#fff8fb',
  inputBorder: '#f2cfe0',
  success: '#4fb17a',
  danger: '#d64f7c',
};

const REGISTER_CHANNEL = 'customer';

export default function RegisterScreen() {
  const router = useRouter();
  const params = useLocalSearchParams<{ redirect?: string }>();
  const { signUp } = useAuth();

  const sanitizedRedirect: RedirectTarget | undefined = useMemo(
    () => normalizeRedirectParam(params.redirect),
    [params.redirect],
  );

  const loginLinkParams = sanitizedRedirect
    ? { redirect: encodeRedirectParam(sanitizedRedirect) }
    : undefined;

  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    const normalizedPhone = phone.replace(/\D/g, '');

    if (normalizedPhone.length !== 11) {
      setError('手机号需为 11 位数字');
      return;
    }

    if (password.trim().length < 6) {
      setError('密码至少 6 位字符');
      return;
    }

    if (password !== confirm) {
      setError('两次输入的密码不一致');
      return;
    }

    setError(null);
    setSubmitting(true);

    try {
      await signUp({ phone: normalizedPhone, password, channel: REGISTER_CHANNEL });
      if (sanitizedRedirect) {
        router.replace(sanitizedRedirect as Href);
      } else {
        router.replace('/');
      }
    } catch (err) {
      if (err instanceof Error) {
        setError(err.message);
      } else {
        setError('注册失败，请稍后再试。');
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.flex}
      >
        <ScrollView
          contentContainerStyle={styles.container}
          showsVerticalScrollIndicator={false}
          bounces={false}
        >
          <View style={styles.hero}>
            <Text style={styles.heroTitle}>注册 PhotoSales+</Text>
            <Text style={styles.heroSubtitle}>
              仅需几步即可完成个人账号注册，系统会自动同步您的订单与相册内容。
            </Text>
          </View>

          <View style={styles.card}>
            <View style={styles.notice}>
              <Text style={styles.noticeTitle}>注册说明</Text>
              <Text style={styles.noticeText}>
                · 当前仅支持个人账号注册，如需商户合作请直接登录商户账号。
              </Text>
              <Text style={styles.noticeText}>
                · 请填写常用手机号，方便顾问与您联系确认服务细节。
              </Text>
            </View>

            <View style={styles.formGroup}>
              <Text style={styles.inputLabel}>手机号</Text>
              <TextInput
                value={phone}
                onChangeText={(value) => setPhone(value.replace(/\D/g, ''))}
                keyboardType="number-pad"
                maxLength={11}
                placeholder="请输入 11 位手机号"
                placeholderTextColor={palette.textMuted}
                style={styles.input}
                returnKeyType="next"
              />
            </View>

            <View style={styles.formGroup}>
              <Text style={styles.inputLabel}>设置密码</Text>
              <TextInput
                value={password}
                onChangeText={setPassword}
                secureTextEntry
                placeholder="至少 6 位字符"
                placeholderTextColor={palette.textMuted}
                style={styles.input}
                returnKeyType="next"
              />
            </View>

            <View style={styles.formGroup}>
              <Text style={styles.inputLabel}>确认密码</Text>
              <TextInput
                value={confirm}
                onChangeText={setConfirm}
                secureTextEntry
                placeholder="请再次输入密码"
                placeholderTextColor={palette.textMuted}
                style={styles.input}
                returnKeyType="done"
              />
            </View>

            {error ? (
              <View style={styles.errorBadge}>
                <Text style={styles.errorText}>{error}</Text>
              </View>
            ) : (
              <View style={styles.tipBadge}>
                <Text style={styles.tipText}>注册完成后将自动登录当前账号。</Text>
              </View>
            )}

            <Pressable
              style={({ pressed }) => [
                styles.submitButton,
                pressed && styles.submitButtonPressed,
                isSubmitting && styles.submitButtonDisabled,
              ]}
              onPress={handleSubmit}
              disabled={isSubmitting}
            >
              <Text style={styles.submitText}>
                {isSubmitting ? '注册中...' : '完成注册并登录'}
              </Text>
            </Pressable>

            <View style={styles.footer}>
              <Text style={styles.footerText}>已有账号？</Text>
              <Link
                href={{ pathname: '/(auth)/login', params: loginLinkParams }}
                asChild
                replace
              >
                <Pressable>
                  <Text style={styles.footerLink}>直接登录</Text>
                </Pressable>
              </Link>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: palette.background,
  },
  flex: {
    flex: 1,
  },
  container: {
    alignItems: 'center',
    paddingHorizontal: 24,
    paddingVertical: 28,
    gap: 24,
  },
  hero: {
    width: '100%',
    maxWidth: 520,
    gap: 8,
  },
  heroTitle: {
    fontSize: 26,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  heroSubtitle: {
    fontSize: 14,
    color: palette.textMuted,
    lineHeight: 20,
  },
  card: {
    width: '100%',
    maxWidth: 520,
    borderRadius: 28,
    padding: 24,
    backgroundColor: palette.card,
    gap: 18,
    shadowColor: '#e2a7c1',
    shadowOpacity: 0.25,
    shadowOffset: { width: 0, height: 8 },
    shadowRadius: 20,
    elevation: 6,
  },
  notice: {
    borderRadius: 20,
    backgroundColor: 'rgba(255,143,177,0.12)',
    padding: 16,
    gap: 6,
  },
  noticeTitle: {
    fontSize: 14,
    fontWeight: '600',
    color: '#d66a8a',
  },
  noticeText: {
    fontSize: 12,
    color: '#6a566a',
    lineHeight: 18,
  },
  formGroup: {
    gap: 8,
  },
  inputLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  input: {
    height: 52,
    borderRadius: 16,
    paddingHorizontal: 16,
    backgroundColor: palette.inputBackground,
    borderWidth: 1,
    borderColor: palette.inputBorder,
    fontSize: 15,
    color: palette.textPrimary,
  },
  tipBadge: {
    borderRadius: 12,
    backgroundColor: 'rgba(79,177,122,0.12)',
    borderWidth: 1,
    borderColor: 'rgba(79,177,122,0.18)',
    paddingHorizontal: 14,
    paddingVertical: 10,
  },
  tipText: {
    color: palette.success,
    fontSize: 13,
  },
  errorBadge: {
    borderRadius: 12,
    backgroundColor: 'rgba(214,79,124,0.12)',
    borderWidth: 1,
    borderColor: 'rgba(214,79,124,0.24)',
    paddingHorizontal: 14,
    paddingVertical: 10,
  },
  errorText: {
    color: palette.danger,
    fontSize: 13,
  },
  submitButton: {
    borderRadius: 18,
    paddingVertical: 14,
    alignItems: 'center',
    backgroundColor: palette.accent,
  },
  submitButtonPressed: {
    backgroundColor: palette.accentDeep,
  },
  submitButtonDisabled: {
    opacity: 0.65,
  },
  submitText: {
    color: palette.textPrimary,
    fontSize: 16,
    fontWeight: '700',
    letterSpacing: 0.3,
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 6,
  },
  footerText: {
    fontSize: 13,
    color: palette.textMuted,
  },
  footerLink: {
    fontSize: 13,
    color: palette.accentDeep,
    fontWeight: '700',
  },
});
